<template>
  <div>
    <div class="list-btn">
      姓名:<Input v-model.trim="params.userName" placeholder="请输入姓名" style="width: 200px" clearable @keyup.enter.native="getList(url)" />

    </div>
    <div class="list-btn">
      手机号:<Input v-model.trim="params.mobile" placeholder="请输入手机号" style="width: 200px" clearable @keyup.enter.native="getList(url)" />

    </div>
    <div class="list-btn">
      用户类别:
      <Select clearable style="width:200px" v-model="params.fb1" placeholder="全部">
        <Option value=" ">全部</Option>
        <Option value="0">系统用户</Option>
        <Option value="1">渠道用户</Option>
        <Option value="2">催收用户</Option>
      </Select>
    </div>
    <div class="list-btn">

      <Button type="primary" @click="getList(url,'refresh')">搜索</Button>
      <Button type="primary" style="margin-left:10px;" @click="showModal.editShow = true;resetFormal();type = '增加';">新增用户</Button>

    </div>
    <page-list :listTitle="listTitle" :list="list" :loading="loading" @selectItem="ids = $event;"></page-list>
    <page-button :current="params.pageCurrent"  :total="total" @changePageNum="params.pageCurrent = $event; getList(url)" @changePageSize="params.pageLimit = $event; getList(url)"></page-button>

    <Modal
      v-model="showModal.isShow"
      :title="title"
      :loading="loading">
      <form>
        <CheckboxGroup v-model="roleIdStr">
          <div v-for="item in roleIdStrList">
            <Checkbox size="large" style="display: block;"  :label="item.id">{{item.name}}</Checkbox>
          </div>
        </CheckboxGroup>
      </form>
      <div style="margin-left: 350px;">
        <Button @click="showModal.isShow = false;">取消</Button>
        <Button type="primary" @click.prevent="roleUpdateData">确定</Button>
      </div>
    </Modal>

    <!--编辑角色-->
    <Modal
      v-model="showModal.editShow"
      :title="`${type}用户`"
      width="500px"
      :closable="true"
      :style="{textAlign:'left'}">
      <Form ref="formRole" :rules="ruleValidate" :model="formRole" :label-width="80">
        <FormItem label="账号" prop="userAccount">
          <Input v-model="formRole.userAccount" :disabled="type == '编辑'?true:false" placeholder="请输入" style="width:200px"></Input>
        </FormItem>
        <FormItem label="密码" prop="password">
          <Input v-model="formRole.password" type="password" placeholder="请输入" style="width:200px"></Input>
        </FormItem>
        <FormItem label="姓名" prop="userName">
          <Input v-model="formRole.userName" placeholder="请输入" style="width:200px"></Input>
        </FormItem>
        <!-- <FormItem label="邮箱地址	" prop="email">
          <Input v-model="formRole.email" placeholder="请输入" style="width:200px"></Input>
        </FormItem> -->
        <FormItem label="手机号" prop="mobile">
          <Input v-model="formRole.mobile" placeholder="请输入" style="width:200px"></Input>
        </FormItem>
        <FormItem label="性别" prop="genderText">
          <Select clearable v-model="formRole.genderText" placeholder="请选择" style="width:200px">
            <Option value="男">男</Option>
            <Option value="女">女</Option>
          </Select>
        </FormItem>
       <!-- <FormItem label="状态" prop="statusText">
          <Select clearable v-model="formRole.statusText" placeholder="请选择" style="width:200px">
            <Option value="0">可用</Option>
            <Option value="1">禁用</Option>
          </Select>
        </FormItem>-->
        <FormItem label="用户类别" prop="fb1">
          <Select clearable v-model="formRole.fb1" placeholder="请选择" style="width:200px">
            <Option value="0">系统用户</Option>
            <Option value="1">渠道用户</Option>
            <Option value="2">催收用户</Option>
          </Select>
        </FormItem>
        <div style="margin-left: 350px;">
          <Button @click="cancel">取消</Button>
          <Button type="primary" @click.prevent="ok">确定</Button>
        </div>
      </Form>
    </Modal>
  </div>
</template>

<script>
  import listMixin from '../../mixin/list'
  import pageList from '../../template/listTemplate'
  import pageButton from '../../template/pageBtnTemplate'
  import confirmDialog from '../../template/confirmDialogTemplate'
  export default {
    mixins:[listMixin],
    components: {
      pageList,
      pageButton,
      confirmDialog
    },
    data () {
      return {
        tag: {
          'title': '用户管理',
          'path': '/work/adminUser/list'
        },
        checkAll:false,
        roleIdStrList:[],
        roleIdStr:[],
        formRole: {
          statusText:'0',
          fb1:'0'
        },
        type:'编辑',
        userId:'',
        ruleValidate: {
          userAccount: [
            { required: true, message: '请填写账号', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请填写密码', trigger: 'blur' }
          ],
           userName: [
            { required: true, message: '请填写姓名', trigger: 'blur' }
          ],
          fb1: [
            { required: true, message: '请选择', trigger: 'blur' }
          ]
        },
        showModal: {
          isShow: false,
          editShow: false,
        },
        title:'',
        listTitle: [
          {
            title: '账号',
            key: 'userAccount',
            align:'center',

            minWidth:120,
          },
          {
            title: '用户姓名',
            key: 'userName',
            align:'center',
            minWidth:120,
            render:(h,params) => {
              return h('div', params.row.userName ? params.row.userName : "—")
            }
          },
          {
            title: '手机号',
            key: 'mobile',
            align:'center',
            minWidth:110,
            render:(h,params) => {
              let phone = params.row.mobile;
              return h('div', phone ? `${phone.substr(0,3)}****${phone.substr(7)}` : "—")
            }
          },
          // {
          //   title: '邮箱',
          //   key: 'email',
          //   align:'center',
          //   minWidth:200,
          //   render:(h,params) => {
          //     return h('div', params.row.email ? params.row.email : "—")
          //   }
          // },
          {
            title: '性别',
            key: 'genderText',
            align:'center',
            minWidth:80,
            render:(h,params) => {
              return h('div', params.row.genderText ? params.row.genderText : "—")
            }
          },
          {
            title: '用户类别',
            key: 'fb1',
            align:'center',
            minWidth:120,
            render:(h,params) => {
              return h('div', params.row.fb1 == 0 ? '系统用户' : params.row.fb1 == 1 ? '渠道用户': "催收用户")
            }
          },
          {
            title: '创建时间',
            key: 'createTime',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              let len = (params.row.createTime).length;
              let text = (params.row.createTime).substr(0,len-2)
              return h('div', text)
            }
          },
          {
            title: '修改时间',
            key: 'updateTime',
            align:'center',
            minWidth:160,
            render:(h,params) => {
              let text = '—';
              if(params.row.updateTime){
                 let len = (params.row.updateTime).length;
                 text = (params.row.updateTime).substr(0,len-2)
              }

              return h('div', text)
            }
          },
          {
            title: '操作人',
            key: 'updatorName',
            align:'center',
            minWidth:100,
            render:(h,params) => {
              return h('div',params.row.updatorName)
            }
          },
           {
            title: '状态',
            key: 'statusText',
            minWidth:100,
            align:'center',
            render: (h, params) => {// 审核状态 0正在审核 1审核通过 2审核拒绝
              let texts = '';
              let props = {};
              switch (params.row.statusText) {
                case '0':
                  texts = '可用';
                  props = {
                    type: "success",
                    size: "small"
                  }
                  break;
                case '1':
                  texts = '禁用';
                  props = {
                    type: "warning",
                    size: "small"
                  }
                  break;
              }
              return h('Button', {
                props: props,
              }, texts)
            },
          },
          {
            title: '操作',
            key: 'action',
            align:'center',
            width: 200,
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.type = '编辑'
                      this.showModal.editShow = true;
                      this.formRole = JSON.parse(JSON.stringify(params.row));
                      // console.log(params)
                    }
                  }
                }, '编辑'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.showModal.isShow = true;
                      this.title = params.row.userName ? params.row.userName : '角色分配';
                      this.getRole(params.row.id);
                      this.userId = params.row.id;
                      // console.log(params)
                    }
                  }
                }, '角色分配'),
                h('Button', {
                  props: {
                    type: 'info',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.$Modal.confirm({
                        title: '提示',
                        content: `<p>是否删除该用户?</p>`,
                        onOk: () => {
                          let data = {};
                          data.id = params.row.id;
                          this.delItem('/sysUser/discard', data);
                        },
                        onCancel: () => {
                        }
                      });
                    }
                  }
                }, '删除'),
              ]);
            }
          },

        ],
        url: '/sysUser/list',
        nameListUrl: '',
        params: {
          pageCurrent: 1,
          pageLimit: 10
        },
        roleTotal:[],
      }
    },
    methods: {
      resetValidate(name) {
        this.$refs[name].resetFields();
      },
      getRole(id){
        this.roleIdStr = [];
        let params = {
          id: id,
          token: sessionStorage.getItem('token')
        }
        let _this = this;
        this.$post('/sysUserRole/RoleList', params)
          .then((res) => {
            if(res.code === 0){
              this.roleIdStrList = res.data.roleList;
              let userRoleList = [];
              userRoleList = res.data.userRolelist;
              // console.log(res.data.userRolelist,'data.userRolelist')
              // console.log(userRoleList,'userRolelist')
              if(userRoleList.length>0){
                userRoleList.map((item) => {
                  this.roleIdStr.push(item.id);
                })

              }else{
                this.roleIdStr = [];
              }
              // console.log(this.roleIdStr,'roleIdStr')
            }
          })
      },
      roleUpdateData () {
        let params = {
          userId: this.userId,
          roleIdStr: this.roleIdStr.join(',')
        };
        this.$post('/sysUserRole/saveOrUpdate', params)
          .then((res) => {
            if(res.code == 0){
              // console.log(res.data)
              this.showModal.isShow = false;
              this.$Message.success('提交成功！');
            }else if(res.code ==1){
               this.$Message.error('当前账号已存在！');
            }
          }, (err) => {
            console.log(err);
          })
      },
      handleCheckAll () {
        // console.log(this.roleTotal)
        if(this.checkAll) {
          this.checkAll = !this.checkAll;
          this.roleIdStr = this.roleTotal;
        }
      },
      cancel() {
        this.showModal.editShow = false;
      },
      ok(){
        this.$refs['formRole'].validate((valid) => {
          if(valid) {
            let url = '';
            if(this.type == '增加'){
              url = '/sysUser/append';
            }else{
              url = '/sysUser/modify';
            }
            // console.log(this.formRole)
            this.$post(url, this.formRole)
              .then((res) => {
                if(res.code === 0){
                  // console.log(res.data)
                  this.showModal.editShow = false;
                  this.$Message.success('提交成功！');
                  this.getList(this.url);
                }else if(res.code == 1){
                  this.$Message.error("禁止重复添加");

                }
              }, (err) => {
                 console.log(err);
              })
          }
        })
      },
      resetFormal(){
        this.formRole={
          statusText:'0',
            fb1:'0'
        };
      }

    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .list-btn{
    margin-bottom: 5px;
    margin-right: 5px;
    display: inline-block;
  }
  .refresh-btn{
    float: right;
  }
  /deep/ .ivu-modal-footer{
    display: none;
  }
</style>
